package jwlee.testjta;

import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.util.Properties;
import javax.transaction.*;

public class JTATest {
	public JTATest() {
	}

	public static void main(String[] args) {
		new JTATest().testJTA();
	}

	public void testJTA() {
		Context ctx = null;
		try {
			ctx = this.getInitialContext();
		} catch (NamingException e4) {
			e4.printStackTrace();
		}

		UserTransaction tx = null;
		try {
			tx = (UserTransaction) ctx.lookup("javax.transaction.UserTransaction");
			tx.begin();//
		} catch (Exception e4) {
			e4.printStackTrace();
		}

		DataSource ds = null;
		try {
			ds = (javax.sql.DataSource) ctx.lookup("mzjds");
		} catch (NamingException e2) {
			e2.printStackTrace();
		}

		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = ds.getConnection();
			stmt = conn.createStatement();
			stmt.executeUpdate("INSERT INTO MZJTEST (ID, NAME) VALUES (1, 'mzj')");
			rs = stmt.executeQuery("SELECT * FROM MZJTEST");
			System.out.println("insert Success!");

			long id;
			String name;
			while (rs.next()) {
				id = rs.getLong("ID");
				name = rs.getString("NAME");
				System.out.println("ID:" + id + " NAME:" + name);
			}
			tx.commit();//
		} catch (Exception e) {
			e.printStackTrace();
			try {
				tx.rollback();//
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			System.out.println("Error message = " + e.getMessage());
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				System.out.println("Error code = " + e.getErrorCode());
				System.out.println("Error message = " + e.getMessage());
			}
		}
	}

	private Context getInitialContext() throws NamingException {
		String factory = "weblogic.jndi.WLInitialContextFactory";
		String url = "t3://localhost:7001";
		String user = "weblogic";
		String password = "weblogic";

		Properties properties = new Properties();
		properties.put(Context.INITIAL_CONTEXT_FACTORY, factory);
		properties.put(Context.PROVIDER_URL, url);
		properties.put(Context.SECURITY_PRINCIPAL, user);
		properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);

		return new InitialContext(properties);
	}
}
